<?php

namespace IDock\Insurance\ZSIC;

use IDock\Common\BaseInterface\BuilderInterface;
use IDock\Common\Tools\XMLTools;
use IDock\Http\Request;
use IDock\Http\Response;
use IDock\Insurance\ZSIC\Request\AllZSICRequest;
use IDock\Insurance\ZSIC\Response\AllZSICResponse;

class Builder implements BuilderInterface
{

    public function getConfig(): array
    {
        return $this->config;
    }

    protected $ip;

    protected $config;

    protected $userCode;

    protected $productCode;
    protected $gateway;

    protected $clientName;
    protected $accessKey;

    public function execute(Request $request): Response
    {
        $channelCode = $this->config['channelCode'] ??'';
        $cityCode = $this->config['cityCode'] ?? '';

        /*** @var AllZSICRequest $request */
        $request->loadConfig($this->config);

        $request->setRequestId(md5(uniqid()));
        $data = $this->generate($request);
        $param = [
            'head' => [
                'businessNo' => $request->getBusinessNo() ?: 'BTX' . date('YmdHis') . mt_rand(1000, 9999),
                'requestCode' => $request->requestCode,
                'businessResource' => $this->config['businessResource'] ?? '',
                'channelCode' =>  $channelCode ?: $request->channelCode,
                'cityCode' => $cityCode ?: $request->cityCode ?: '510100'
            ],
            'body' => $data
        ];
        $xml = XMLTools::ToXML($param, 'request');
        $xml = '<?xml version="1.0" encoding="utf-8"?>' . $xml;
        $request->setPreParameter($xml);
        $request->setBizParam($xml);
        $request = $this->sign($request);
        return $this->request($request);
    }

    public function generate(Request $request): array
    {
        return $request->generate();
    }

    public function sign(Request $request): Request
    {
        $sign = md5($request->getBizParam() . ($this->config['secertKey'] ?? ''));
        $request->setGateway($this->gateway . '?accessKey=' . $this->accessKey . '&signature=' . $sign);
        return $request;
    }


    public function exceptionResponse($request, $errorMessage): Response
    {
        $response = $request->getResponse();

        $response = new $response;
        $response->setCode('500');
        $response->setError($errorMessage);

        return $response;
    }

    public function request(Request $request): Response
    {
        /**
         * @var AllZSICResponse $response
         */
        $response = $request->request($request);
        $response->setVisitor($request->getVisitor());

        if ($response->isSuccess()) {
            $response->printerInit();
        }
        return $response;
    }

    /**
     * 数据加密
     * @param Request $request
     */
    public function encrypt(Request $request)
    {

    }

}


